import json
import requests

from public.config import redisUser, log, secret, sign


def getip(num, time):
    url = f"http://api.tianqiip.com/getip?secret={secret}&num={num}&type=json&region=440000&port=1&time={time}&ts=1&ys=1&cs=1&mr=1&sign={sign}"
    response = requests.request("GET", url)
    text = json.loads(response.text)
    data =text.get("data")[0]
    ip = data["ip"]
    port = data["port"]
    proxy = f"{ip}:{port}"
    return proxy

expireTime = 5
def getProxy(mobile,tid):
    proxy = redisUser.GetKey(f"proxyPool:{mobile}")
    if proxy:
        log.info(f"缓存里获取到的ip:{proxy}", tid)
        if check_proxy(proxy):
            log.info(f"缓存里获取到的ip:{proxy}有效", tid)
            return proxy
        else:
            proxy = getip(1, expireTime)
            redisUser.SetKey(f"proxyPool:{mobile}", proxy)
            log.info(f"缓存里获取到的ip无效，重新获取ip:{proxy}", tid)
            return proxy
    else:
        proxy = getip(1, expireTime)
        redisUser.SetKey(f"proxyPool:{mobile}", proxy)
        log.info(f"缓存里没有对应代理ip，新获取一个{proxy}", tid)
        return proxy

def check_proxy(proxy):
    try:
        response = requests.get('http://www.baidu.com', proxies={"http": "http://"+proxy, "https": "http://"+proxy}, timeout=3)
        # 如果响应状态码为200，则认为代理有效
        return response.status_code == 200
    except requests.RequestException:
        # 如果发生异常，则认为代理无效
        return False

